﻿using System;
using System.Text;
using System.Collections.Generic;

/*
 * Write a program that reverses the words in given sentence.
 * Example: "C# is not C++, not PHP and not Delphi!" -> "Delphi not and PHP, not C++ not is C#!".
 */

namespace ReverseWords
{
    class ReverseWords
    {
        static string Punctuation(string word)
        {
            char[] punctuationSymbols = { '!', ',', '.', '?', ':', ';', '/' };
            StringBuilder symbols = new StringBuilder();

            foreach (char character in word)
            {
                foreach (char symbol in punctuationSymbols)
                {
                    if (char.IsLetter(character))
                    {
                        break;
                    }
                    if (character == symbol)
                    {
                        symbols.Append(symbol);
                    }
                }
            }

            return symbols.ToString();
        }

        static string WordReverse(string text)
        {
            Dictionary<int, string> punctuation = new Dictionary<int, string>();
            StringBuilder result = new StringBuilder();
            string[] words = text.Split(' ');

            for (int wordIndex = 0, length = words.Length; wordIndex < length; wordIndex++)
            {
                string word = words[wordIndex];
                string punctuations = Punctuation(word);
                if (punctuations.Length > 0)
                {
                    punctuation.Add(wordIndex, punctuations);
                    words[wordIndex] = word.Substring(0, word.Length - punctuations.Length);
                }
            }

            for (int i = words.Length - 1, wordsLength = words.Length - 1; i >= 0; i--)
            {
                result.Append(words[i]);
                if (punctuation.ContainsKey(wordsLength - i))
                {
                    result.Append(punctuation[wordsLength - i]);
                }
                result.Append(' ');
            }

            return result.ToString();
        }

        static void Main()
        {
            string text = "C# is not C++, not PHP and not Delphi!?!";
            Console.WriteLine(text);
            Console.WriteLine(WordReverse(text));
        }
    }
}
